package com.yihukurama.sysbase.sysservice.impl;

import com.yihukurama.base.app.cache.RedisUtils;
import com.yihukurama.base.app.exception.TipsException;
import com.yihukurama.base.app.utils.LogUtil;
import com.yihukurama.base.app.utils.TreeUtils;
import com.yihukurama.base.framework.domain.tkmapper.entity.BaseTreeEntity;
import com.yihukurama.base.framework.web.dto.Request;
import com.yihukurama.base.framework.web.dto.Result;
import com.yihukurama.sysbase.common.enums.UserConstants;
import com.yihukurama.sysbase.common.utils.StringUtils;
import com.yihukurama.sysbase.controller.vo.MetaVo;
import com.yihukurama.sysbase.controller.vo.RouterVo;
import com.yihukurama.sysbase.framework.domain.Menu;
import com.yihukurama.sysbase.framework.domain.User;
import com.yihukurama.sysbase.framework.domainservice.MenuService;
import com.yihukurama.sysbase.framework.domainservice.RoleprivilegeService;
import com.yihukurama.sysbase.framework.entity.FuncEntity;
import com.yihukurama.sysbase.framework.entity.MenuEntity;
import com.yihukurama.sysbase.framework.entity.RoleprivilegeEntity;
import com.yihukurama.sysbase.framework.entity.UserroleEntity;
import com.yihukurama.sysbase.framework.mapper.UserroleMapper;
import com.yihukurama.sysbase.sysservice.ISystem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 说明： 系统服务
 * @Author yihukurama
 * @date Created in 15:26 2023/2/10
 *       Modified by yihukurama in 15:26 2023/2/10
 */
@Service
public class SystemService implements ISystem {

    @Autowired
    RedisUtils redisUtils;
    @Autowired
    UserroleMapper userroleMapper;
    @Autowired
    RoleprivilegeService roleprivilegeService;
    @Autowired
    MenuService menuService;
    @Autowired
    TreeUtils treeUtils;


    @Override
    public Result changePassword(Request<User> request) throws TipsException {
        return null;
    }

    @Override
    public Result logout(Request<User> request) throws TipsException {
        User user = request.getData();
        String token = user.getToken();
        if(redisUtils.exists(user.getToken())){
            String uid = (String) redisUtils.get(user.getToken());
            redisUtils.remove(token);
            if(redisUtils.exists(uid)){
                redisUtils.remove(uid);
            }
        }
        return Result.successed("登出成功");
    }

    @Override
    public Result getRoutes(Request<User> request) throws TipsException {
        //获取用户角色
        UserroleEntity userroleEntity = new UserroleEntity();
        userroleEntity.setUserId(request.getData().getId());
        List<UserroleEntity> userroleEntities = userroleMapper.select(userroleEntity);
        List<String> roleIds=new ArrayList<>();
        List<MenuEntity> menus=new ArrayList<>();
        List<FuncEntity> funcs=new ArrayList<>();
        for (UserroleEntity entity : userroleEntities) {
            roleIds.add(entity.getRoleId());
            //获取用户可访问菜单
            RoleprivilegeEntity roleprivilegeEntity = new RoleprivilegeEntity();
            roleprivilegeEntity.setRoleId(entity.getRoleId());
            List<RoleprivilegeEntity> list = roleprivilegeService.list(roleprivilegeEntity);
            for (RoleprivilegeEntity roleprivileget : list) {
                    MenuEntity menuEntity = new MenuEntity();
                    menuEntity.setId(roleprivileget.getPrivilegeId());
                    MenuEntity load = menuService.load(menuEntity);
                    if (load == null || !load.getParentId().equals(BaseTreeEntity.ROOT)) {
                        continue;
                    }
                    menus.add(load);

            }
        }


        List<Menu> allMenus = treeUtils.treeList(menus, Menu.class,"com.yihukurama.sysbase.framework.domainservice.");


//        List<RouterVo> routerVoList = buildMenus(allMenus);
//        return Result.successed(routerVoList);

        return Result.successed(allMenus);
    }



    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus(List<Menu> menus)
    {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (Menu menu : menus)
        {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getText(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache().toString()), menu.getPath()));
            List<Menu> cMenus = menu.getChildren();
            LogUtil.debugLog(this,"要识别的菜单是===>"+menu.getText());
            if (StringUtils.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType()))
            {
                LogUtil.debugLog(this,"父子菜单===>"+menu.getText()+"  "+menu.getParentId());
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));

            }
            else if (isMenuFrame(menu))
            {
                LogUtil.debugLog(this,"一级菜单===>"+menu.getText()+"  "+menu.getParentId());

                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getText(), menu.getIcon(), StringUtils.equals("1", menu.getIsCache().toString()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);

            }
            else if (menu.getParentId().equals("root") && isInnerLink(menu))
            {
                LogUtil.debugLog(this,"内链组件===>"+menu.getText()+"  "+menu.getParentId());

                router.setMeta(new MetaVo(menu.getText(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getText(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);

            }else if(StringUtils.isNotEmpty(cMenus)){
                LogUtil.debugLog(this,"未匹配菜单类型，为子菜单，跳过"+menu.getText());

            }
            routers.add(router);
        }
        return routers;
    }


    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path)
    {
        return StringUtils.replaceEach(path, new String[] { "http://", "https://", "www", "." },
                new String[] { "", "", "", "/" });
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(Menu menu)
    {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(Menu menu)
    {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (!menu.getParentId().equals("root") && isInnerLink(menu))
        {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (menu.getParentId().equals("root") && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame().toString()))
        {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(Menu menu)
    {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu))
        {
            component = menu.getComponent();
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && !menu.getParentId().equals("root") && isInnerLink(menu))
        {
            component = UserConstants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu))
        {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(Menu menu)
    {
        return menu.getParentId().equals("root") && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().toString().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(Menu menu)
    {
        return menu.getIsFrame().toString().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(Menu menu)
    {
        return (!menu.getParentId().equals("root")) && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }


}
